﻿using System;
using System.Windows.Data;

namespace OpenLightGroup.Common.Converters
{
    /// <summary>
    /// Converter to truncate strings if the length is over the specified amount.
    /// </summary>
    public class StringTruncateConverter : IValueConverter
    {

        #region IValueConverter Members
        /// <summary>
        /// Returns a truncated string with a trailing ... if the string length is over the specified length.
        /// </summary>
        /// <param name="value">String to evaluate</param>
        /// <param name="targetType">Not used</param>
        /// <param name="parameter">Maximum length of the string.</param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int maxLength;
            if (parameter != null && int.TryParse(parameter.ToString(), out maxLength))
            {
                string val = (value == null) ? null : value.ToString();
                if (val != null && val.Length > maxLength)
                {
                    return val.Substring(0, maxLength) + "...";
                }
            }
            return value;
        }

        /// <summary>
        /// Not implemented.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

}
